package cn.edu.nyist.integration.controller;


import cn.edu.nyist.integration.common.Const;
import cn.edu.nyist.integration.common.ResponseCode;
import cn.edu.nyist.integration.common.ServerResponse;
import cn.edu.nyist.integration.config.ServerConfig;
import cn.edu.nyist.integration.entity.User;
import cn.edu.nyist.integration.service.LogInfoService;
import cn.edu.nyist.integration.service.UserService;
import cn.edu.nyist.integration.util.FileUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.util.UUID;

/**
 * @author 胡
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LogInfoService logInfoService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping("/")
    public String toLoginPage() {
        return "page/login";
    }

    /**
     * 跳转到注册界面
     *
     * @return
     */
    @RequestMapping("/to_register")
    public String toRegister() {
        return "page/register";
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpServletRequest request, RedirectAttributes model) {
        ServerResponse<User> login = userService.login(username, password);
        User user = login.getData();
        /*登陆成功*/
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        if (login.isSuccess()) {
            session.setAttribute("user", login.getData());
            session.setMaxInactiveInterval(60 * 30);
            if (user.getRole() == 1) {
                return "page/admin";
            }
            return "page/index";
        }
        /*登陆失败*/
        model.addFlashAttribute("errorMsg", login.getMsg());
        System.out.println(login.getMsg());
        return "redirect:/user/";
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping("/register")
    public ServerResponse<String> register(User user) {
        ServerResponse<String> response = userService.register(user);
        return response;
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "page/login";
    }

    /**
     * 查看个人信息
     */
    @RequestMapping(value = "/get_info", method = RequestMethod.GET)
    public String getUserInfo(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            model.addAttribute("userInfo", user);
        }
        model.addAttribute("error", Const.NO_LOGIN);
        return "page/user-setting";

    }

    /**
     * 修改用户信息
     *
     * @param user
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update_info", method = RequestMethod.POST)
    public ServerResponse<User> updateUser(User user, HttpSession session) {
        User currentUser = (User) session.getAttribute("user");


        if (currentUser == null) {
            return ServerResponse.createByErrorMessage("需要登陆,才能修改");
        }
        user.setUsername(currentUser.getUsername());
        user.setId(currentUser.getId());
        user.setRole(currentUser.getRole());
        user.setSex(currentUser.getSex());
        user.setAvatar(currentUser.getAvatar());
        user.setStatus(currentUser.getStatus());
        user.setLoginTime(currentUser.getLoginTime());
        user.setPassword(null);
        ServerResponse<User> response = userService.updateInformation(user);
        User data = response.getData();

        if (response.isSuccess()) {
            //更新成功后，session中的user也要更新
            session.setAttribute("user", data);
        }
        return response;
    }


    /**
     * 获取密保问题
     *
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/get_question")
    public String getQuestion(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/";
        }
        model.addAttribute("question", user.getQuestion());
        return "page/user-answer";
    }

    /**
     * 检测密保问题
     *
     * @param question
     * @param answer
     * @param session
     * @return
     */
    @RequestMapping("/checkAnswer")
    @ResponseBody
    public ServerResponse<User> checkAnswer(@RequestParam String question, @RequestParam String answer, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ServerResponse.createByErrorMessage("登录失效，请重新登录");
        }
        return userService.checkAnswer(question, answer, user.getId());

    }

    /**
     * 去修改密码页面
     *
     * @return
     */
    @RequestMapping("/password")
    public String toPassword() {
        return "page/user-password";
    }

    /**
     * 重置密码
     *
     * @param session
     * @param passwordOld
     * @param passwordNew
     * @return
     */
    @RequestMapping(value = "/reset_password", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> resetPassword(HttpSession session,
                                                @RequestParam String passwordOld,
                                                @RequestParam String passwordNew) {
        System.out.println("old password: " + passwordOld);
        System.out.println("new password: " + passwordNew);
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }
        return userService.resetPassword(passwordOld, passwordNew, user);
    }

    /**
     * 查询登录日志
     */
    @RequestMapping(value = "/log_info", method = RequestMethod.GET)
    public String listLogInfo(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "6") int pageSize,
                              HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            //session过期重新登录
            return "redirect:/user/";
        }
        PageInfo pageInfo = userService.selectAllLogInfo(pageNum, pageSize, user.getUsername());

        model.addAttribute("pageInfo", pageInfo);
        return "page/log_info";
    }

    /**
     * 删除登录日志
     *
     * @param log_id
     * @return
     */
    @RequestMapping("/del_log")
    public String deleteLog(@RequestParam Integer log_id) {
        if (logInfoService.deleteLog(log_id).isSuccess()) {
            //删除成功
            return "redirect:/user/log_info";
        }
        return "error";
    }

    /**头像替换
     *
     * @param file
     * @param session
     * @return
     */
    @PostMapping("/projectPictureUpload")
    @ResponseBody
    public ServerResponse fileUpload(@RequestParam(value = "projectImg", required = true)
                                             MultipartFile file, HttpSession session) {
        if (file.isEmpty()) {
            return ServerResponse.createByErrorMessage("图片不能为空");
        }
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件名用UUID防止重复
        String filename = UUID.randomUUID().toString().replace("-", "") + suffix;
        String osName = System.getProperty("os.name");
        //文件保存路径
        String filePath = "";
        if (osName.toLowerCase().startsWith("win")) {
            //windows下的路径
            filePath = "d:/pictureUpload/project/";
        } else {
            //linux下的路径
            filePath = "/root/pictureUpload/project/";
        }
        try {
            //开始上传文件
            Boolean uploadFile = FileUtil.uploadFile(file.getBytes(), filePath, filename);
            if (uploadFile == false) {
                return ServerResponse.createByErrorMessage("文件上传失败");
            }
            String url = serverConfig.getUrl();

            String fullPath = "/pictureUpload/project/" + filename;
            String imgUrl = url + fullPath;
            //修改该用户的头像
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), "登录过期，请重新登录");
            }
            user.setAvatar(imgUrl);
            System.out.println("session user= " + user);
            userService.updateInformation(user);
            return ServerResponse.createBySuccessMessageData("上传成功", imgUrl);

        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件上传失败");
        }


    }


}
